﻿#include "cinihelp.h"
#include <QTextCodec>
#include <QCoreApplication>
#include <QFile>

CIniHelp::CIniHelp(QObject *parent) : QObject(parent)
{

}

CIniHelp::~CIniHelp()
{
    m_iniFile->deleteLater();
}

void CIniHelp::settingsInit(const QString &sPath)
{
    m_iniFile = QSharedPointer<QSettings>(new QSettings(sPath, QSettings::IniFormat));
    //确保中文能使用
    //注意此处使用的编码取决于ini文件的编码格式，例如ini使用的是UTF-8则使用UTF-8
    #ifdef Q_OS_WIN32//windows
    m_iniFile->setIniCodec(QTextCodec::codecForName("GBK"));
    #else//arm
    m_iniFile->setIniCodec(QTextCodec::codecForName("UTF-8"));
    #endif
}

void CIniHelp::setValue(const QString &sSection, const QString &sKey, const QString &sValue)
{
    m_iniFile->beginGroup(sSection);// 设置节点名
    m_iniFile->setValue(sKey, sValue);//设置键名和键值
    m_iniFile->endGroup();// 结束当前节的操作
    m_iniFile->sync();

}

void CIniHelp::removeNode(const QString &sSection)
{
    m_iniFile->remove(sSection);
}

void CIniHelp::removeKey(const QString &sSection, const QString &sKey)
{
    m_iniFile->beginGroup(sSection);
    m_iniFile->remove(sKey);
    m_iniFile->endGroup();
}

QString CIniHelp::getValue(const QString &sSection, const QString &sKey, const QString &sDefaultValue)
{
    QString strPath = QObject::tr("%1/%2").arg(sSection).arg(sKey);
    #ifdef Q_OS_WIN32//windows
    QString strResult = QString::fromUtf8(m_iniFile->value(strPath, sDefaultValue).toString().toUtf8());//中文问题
    #else//arm
    QString strResult = m_iniFile->value(strPath, strDefaultValue).toString();
    #endif
    return strResult;
}

QStringList CIniHelp::getValueList(const QString & sSection, const QString &sKey, QString sDefaultValue)
{
    QVariant variant = m_iniFile->value(QString("%1/").arg(sSection) + sKey);
    QStringList list = variant.value<QStringList>();
    return list;
}
